﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Drawing;
using simple.Utilities;
using System.Drawing.Imaging;
using System.IO;
using simpleHotel.Data;
using System.Text;

namespace simpleHotel.Web
{
 
    /// <summary>
    /// Description
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class HotelService : System.Web.Services.WebService
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>      
        #region ================ Hotel Function =====================
        /// <summary>
        /// Get All Hotel
        /// </summary>
        /// <returns>Hotel Table</returns>
        [WebMethod]
        public DataTable GetAllHotels()
        {
            return DataProvider.ExecuteDataSet("getAllHotel").Tables[0];
        }
        /// <summary>
        /// Get Service By HotelID
        /// </summary>
        /// <param name="hotelID"></param>
        /// <returns></returns>
        [WebMethod]
        public DataTable GetServiceByHotelID(int hotelID)
        {
            return DataProvider.ExecuteDataSet("GetServiceByHotelID").Tables[0];
        }
        /// <summary>
        /// Get Cate Room by HotelID
        /// </summary>
        /// <param name="hotelID"></param>
        /// <returns></returns>
        [WebMethod]
        public DataTable GetCateRoomHotelID(int hotelID)
        {
            return DataProvider.ExecuteDataSet("GetCateRoomByHotelID", hotelID).Tables[0];
        }
        [WebMethod]
        public DataTable GetHotel(int hotelId) 
        {            
            return DataProvider.ExecuteDataSet("getHotelByID", hotelId).Tables[0];           
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        [WebMethod]
        public string UpdateHotel(HotelInfoDTO info) 
        {
            DataProvider.ExecuteNonQuery("updateHotelInfo", info.ID, info.HotelName, info.Price, info.RegionID, info.ServiceID,
                                        info.TotalRoom, info.image, info.Description, info.Address1, info.Email, info.Phone1, info.Fax,info.phone2,info.Address2,info.Address3);
            return string.Empty;
        }
        [WebMethod]
        public string updateHotelImage(HotelInfoDTO info)
        {
         
                //create folder for hotel
                string imageFolder = HotelHelper.GetImageFolder(info.ID.ToString());
                string smallImageFolder = HotelHelper.GetSmallImagesFolder(info.ID.ToString());

                //save big image
                var image = ImageHelper.Base64ToImage(info.image);
                if (image != null)
                    image.Save(imageFolder + "\\image.jpg", ImageFormat.Jpeg);
                string dbImage = imageFolder + "\\image.jpg";

                //save small images
                var dbSmallList = new StringBuilder();
                if (info.SmallImages != null && info.SmallImages.Length > 0)
                {
                    int index = 1;
                    foreach (var smImage in info.SmallImages)
                    {
                        var img = ImageHelper.Base64ToImage(smImage);
                        string imgName = smallImageFolder + "\\smallimage_" + (index++).ToString() + ".jpg";
                        img.Save(imgName, ImageFormat.Jpeg);
                        dbSmallList.Append(imgName + ";");
                    }
                }
                string dbSmallImages = dbSmallList.ToString().Trim(';');

                var spList2 = new List<SPParam>();
                spList2.Add(new SPParam { Name = "@HotelID", Value = info.ID, SqlType = SqlDbType.Int });
                spList2.Add(new SPParam { Name = "@Images", Value = dbImage, SqlType = SqlDbType.NVarChar });
                spList2.Add(new SPParam { Name = "@SmallImages", Value = dbSmallImages, SqlType = SqlDbType.NVarChar });

                DataProvider.ExecuteNonQuery("UpdateImageHotel", spList2);
            
            return string.Empty;
        }
        [WebMethod]
        public int CreateHotel(HotelInfoDTO info)
        {
            int ID = 0;

            var spList = new List<SPParam>();
            spList.Add(new SPParam { Name = "@HotelName", SqlType = SqlDbType.NVarChar, Value = info.HotelName });
            spList.Add(new SPParam { Name = "@Price", SqlType = SqlDbType.Money, Value = info.Price });
            spList.Add(new SPParam { Name = "@ProvinceID", SqlType = SqlDbType.Int, Value = info.ProvinceID });
            spList.Add(new SPParam { Name = "@RangeID", SqlType = SqlDbType.Int, Value = info.RangeID });
            spList.Add(new SPParam { Name = "@ServiceID", SqlType = SqlDbType.Int, Value = info.ServiceID });
            spList.Add(new SPParam { Name = "@TotalRoom", SqlType = SqlDbType.Int, Value = info.TotalRoom });
            spList.Add(new SPParam { Name = "@Images", SqlType = SqlDbType.NVarChar, Value = string.Empty });       //first, empty
            spList.Add(new SPParam { Name = "@SmallImages", SqlType = SqlDbType.NVarChar, Value = string.Empty });  //first, empty
            spList.Add(new SPParam { Name = "@Description", SqlType = SqlDbType.NVarChar, Value = info.Description });
            spList.Add(new SPParam { Name = "@Address1", SqlType = SqlDbType.NVarChar, Value = info.Address1 });
            spList.Add(new SPParam { Name = "@Email", SqlType = SqlDbType.NVarChar, Value = info.Email });
            spList.Add(new SPParam { Name = "@Phone1", SqlType = SqlDbType.NVarChar, Value = info.Phone1 });
            spList.Add(new SPParam { Name = "@Fax", SqlType = SqlDbType.NVarChar, Value = info.Fax });
            spList.Add(new SPParam { Name = "@Phone2", SqlType = SqlDbType.NVarChar, Value = info.phone2 });
            spList.Add(new SPParam { Name = "@Address2", SqlType = SqlDbType.NVarChar, Value = info.Address2 });
            spList.Add(new SPParam { Name = "@Address3", SqlType = SqlDbType.NVarChar, Value = info.Address3 });
            spList.Add(new SPParam { Name = "@InsertedID", SqlType = SqlDbType.Int, IsOutput = true });

            //DataProvider.ExecuteNonQuery("createNewHotel", info.HotelName, info.Price, info.RegionID, info.RangeID, info.ServiceID, info.TotalRoom,
            //null, info.Description, info.Address1, info.Email, info.Phone1, info.Fax, info.phone2, info.Address2, info.Address3, ID);

            DataProvider.ExecuteNonQuery("createNewHotel", spList);
            var outParam = spList.FirstOrDefault(x => x.Name == "@InsertedID");
            if (outParam != null)
                ID = (int)outParam.Value;

            if (ID > 0)
            {
                //create folder for hotel
                string imageFolder = HotelHelper.GetImageFolder(ID.ToString());
                string smallImageFolder = HotelHelper.GetSmallImagesFolder(ID.ToString());
                
                //save big image
                var image = ImageHelper.Base64ToImage(info.image);
                if (image != null)
                    image.Save(imageFolder + "\\image.jpg", ImageFormat.Jpeg);
                string dbImage = imageFolder + "\\image.jpg";

                //save small images
                var dbSmallList = new StringBuilder();
                if (info.SmallImages != null && info.SmallImages.Length > 0) 
                {
                    int index = 1;
                    foreach(var smImage in info.SmallImages)
                    {
                        var img = ImageHelper.Base64ToImage(smImage);
                        string imgName = smallImageFolder + "\\smallimage_" + (index++).ToString() + ".jpg";
                        img.Save(imgName, ImageFormat.Jpeg);
                        dbSmallList.Append(imgName + ";");
                    }
                }
                string dbSmallImages = dbSmallList.ToString().Trim(';');

                var spList2 = new List<SPParam>();
                spList2.Add(new SPParam { Name = "@HotelID", Value = ID, SqlType = SqlDbType.Int });
                spList2.Add(new SPParam { Name = "@Images", Value = dbImage, SqlType = SqlDbType.NVarChar });
                spList2.Add(new SPParam { Name = "@SmallImages", Value = dbSmallImages, SqlType = SqlDbType.NVarChar });

                DataProvider.ExecuteNonQuery("UpdateImageHotel", spList2);
            }

            return ID;
        }

        [WebMethod]
        public string DeleteHotel(HotelInfoDTO info) 
        {
            DataProvider.ExecuteNonQuery("DelHotelByID", info.ID);
            return string.Empty;
        }

        [WebMethod(Description="Update available rooms")]
        public string UpdateAvailableRooms(AvailableRoomDTO availableInfo) 
        {
            try
            {
                if (availableInfo != null && availableInfo.Count != null){
                    var builder = new StringBuilder();
                    for(int i=0; i<availableInfo.Count.Length; i++)
                    {
                        builder.AppendFormat(
                            "INSERT INTO MapHotelRoomAvailables(HotelId, RoomCategoryId, AvailableCount, FromDate, ToDate) VALUES({0},{1},{2},'{3}','{4}');",
                            availableInfo.HotelId, availableInfo.RoomCategoryId[i], availableInfo.Count[i],
                            availableInfo.StartDate.ToString(), availableInfo.StartDate.ToString());
                    }

                    return DataProvider.ExecuteNonQuery(builder.ToString().Trim(';'));
                }

                return "Error in DTO object";
            }
            catch (Exception ex) 
            {
                return ex.ToString();    
            }
        }

        [WebMethod(Description="Get room categories by hotel id")]
        public DataTable GetRoomCategoriesByHotelId(int hotelId) {
            var list = new List<SPParam>();
            list.Add(new SPParam { Name = "@hotelId", SqlType = SqlDbType.Int, Value = hotelId });
            var result = DataProvider.ExecuteDataSet("GetRoomCategoriesByHotelId", list).Tables[0];
            result.TableName = "tbRoomCats";

            return result;

        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postedImage"></param>
        /// <param name="IDFolder"></param>
        /// <returns></returns>    
        /// 
        private string ImageUploadData(HttpPostedFile postedImage, int IDFolder)
        {
            string path = Server.MapPath("~/ImageData/" + IDFolder.ToString());
            
            string imgSave = path + "/" + postedImage.FileName.ToString();
            if (!System.IO.Directory.Exists(path))
            {
                Directory.CreateDirectory(Server.MapPath("~/ImageData/" + IDFolder.ToString()));
                ImageUpload ulUpload = new ImageUpload();
                ulUpload.UploadImage(postedImage, path, 40, 50, "");
            }
            return imgSave;
        }


        #region ========================== News Method ============================
        [WebMethod]
        public int createNew(ObjNews info, object postedImage)
        {
            int ID = 0;
            DataProvider.ExecuteNonQuery("CreateNewsData", info.Title, info.News, info.Description,
            info.CategoryID, info.CreatedDate, info.ModifiedDate, info.status, info.image);
            if (ID > 0)
            {
                string imgSave = ImageUploadData((HttpPostedFile)postedImage, ID);
                DataProvider.ExecuteNonQuery("UpdateImageNews");
            }
            return ID;
        }

        [WebMethod]
        public void DeleteNews(int id)
        {
            DataProvider.ExecuteNonQuery("DelNewsByID", id);
        }
        #endregion

        #region ================== User function ===========================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [WebMethod]
        public DataTable IsLogin(ObjAdminDTO info)
        {
            return DataProvider.ExecuteDataSet("IsLogin", info.UserName, info.Password).Tables[0];       
        }

        [WebMethod(Description="Get all users")]
        public DataTable GetAllUsers() 
        {
            var table = DataProvider.ExecuteDataSet("GetAllUsers").Tables[0];
            table.TableName = "tbUsers";
            return table;
        }

        [WebMethod(Description = "Get all roles")]
        public DataTable GetAllRoles()
        {
            var table = DataProvider.ExecuteDataSet("GetAllRoles").Tables[0];
            table.TableName = "tbRoles";
            return table;
        }
        [WebMethod(Description = "Get Roles By HotelID")]
        public string GetRoleByID(int hotelID)
        {
            string roles = DataProvider.ExecuteDataSet("getRolebyHotelID", hotelID).Tables[0].Rows[0][0].ToString();
            return roles;
        }

        [WebMethod]
        public DataTable GetUser(string userName, string password) {
            var list = new List<SPParam>();
            list.Add(new SPParam { Name="@Username", SqlType=SqlDbType.NVarChar });
            list.Add(new SPParam { Name="@Password", SqlType=SqlDbType.NVarChar });

            var table = DataProvider.ExecuteDataSet("GetUser", list).Tables[0];
            table.TableName = "tbUser";
            return table;
        }

        [WebMethod]
        public string DeleteUser(int userId) {
            var list = new List<SPParam>{
                new SPParam { Name="@UserId", Value = userId, SqlType=SqlDbType.Int }
            };
            try
            {
                DataProvider.ExecuteNonQuery("DeleteUser", list);
                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        [WebMethod]
        public string UpdateUser(UserInfoDTO info) { 
            //if have error, return exception message
            return null;
        }

        #endregion


        #region "Booking function"

        [WebMethod]
        public DataTable GetBookingByHotelID(ObjBookings info)
        {
            return DataProvider.ExecuteDataSet("GetBookingByHotelID", info.ID).Tables[0];                    
        }

        [WebMethod]
        public DataTable GetAllBookings()
        {
            return DataProvider.ExecuteDataSet("getAllBooking").Tables[0];
        }

        [WebMethod]
        public DataTable GetAllBookingsAfter(DateTime datetime)
        {
            return DataProvider.ExecuteDataSet("getAllBookingAfter").Tables[0];
        }

        [WebMethod]
        public DataTable GetBooking(ObjBookings info)
        {
            return DataProvider.ExecuteDataSet("getAllBookingByID", info.ID).Tables[0]; ;
        }

        [WebMethod]
        public string UpdateBooking( ObjBookings info)
        {
            return string.Empty;
        }
        [WebMethod]
        public string DeleteBooking(ObjBookings info)
        {
            DataProvider.ExecuteNonQuery("DelBookingByID", info.ID);
            return string.Empty;
        }
        #endregion


        #region ============ Thông Tin cơ bản - Load Quốc Gia/Tỉnh,... ==============

        [WebMethod]
        public DataTable LoadCountry()
        {
            return DataProvider.ExecuteDataSet("LoadCountry").Tables[0];
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public DataTable LoadProvince()
        {
            return DataProvider.ExecuteDataSet("LoadProvince").Tables[0];
        }

        /// <summary>
        /// Load hotel's standard, like 1 star, 2 star, ...
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public DataTable LoadStandards()
        {
            return DataProvider.ExecuteDataSet("LoadStandards").Tables[0];
        }

        [WebMethod]
        public DataTable LoadCateHotel()
        {
            return DataProvider.ExecuteDataSet("LoadCateHotel").Tables[0];
        }
        #endregion

        //[WebMethod]
        //public string GetImage() 
        //{
        //    const string PATH = @"C:\Images\img1.jpg";
        //    var img = Image.FromFile(PATH);
        //    if (img != null) 
        //    {
        //        var result = ImageHelper.ImageToBase64(img, ImageFormat.Jpeg);
        //        return result;
        //    }

        //    return string.Empty;
        //}
    }
}